define(function (require) {
    var doT = require('doT');
    require('table');
    require('treegrid');
    require('bootstrapValidator');
    require('messager');
    require('doctor-select');
    require('doctor-data');
    require('iCheck');
    require('jquery.ztree');

    $.module("BASE.Org", function () {
        return {
            init: function () {
                // this.loadData();
                this.getOrgVersionDetail();

                this.loadEvent();
            },
            clearDatas(){
                $("#fm input[name='_id']").val('');
                $("#fm input[name='parent_id']").val('');
                $("#fm input[name='Name']").val('');

                $("#fm input[name='Flag'][value='0']").iCheck('check');

                $("#fm input[name='NodeLevel']").val('');
                $("#fm input[name='sort']").val(1);
                $('#fm').bootstrapValidator('resetForm', true);

                $("#fm_company #CompanyId").val('').removeAttr('data-id');
                $('#fm_company').bootstrapValidator('resetForm', true);

                $("#fm_costCenter #CompanyId").val('').removeAttr('data-id');
                $("#fm_costCenter #CostCenterId").val('').removeAttr('data-id');
                $('#fm_costCenter').bootstrapValidator('resetForm', true);
            },
            getOrgVersionDetail(){
                var that = this;

                //根据id获取菜单信息
                SYS.Core.ajax({
                    url: "base/orgVersion/active",
                    common: {},
                    data: {},
                    success: function (data) {
                        if(data.code == 1){
                            //填充表单
                            let orgVersionInfo = data.data;
                            $('#s_OrgVersionId').val(orgVersionInfo.Version);
                            $('#s_OrgVersionId').attr('data-id', orgVersionInfo.Id);

                            if (orgVersionInfo.Id) {
                                // 默认查询
                                that.loadData(orgVersionInfo.Id);
                            }
                        }
                    }
                });
            },
            loadData: function (orgVersionId, showAll=false) {
                SYS.Core.ajax({
                    url: 'base/org/treeList',
                    common: {},
                    data: {
                        OrgVersionId: orgVersionId
                    },
                    success: function (data) {
                        let template = doT.template($("#tmpl_org_list").html());
                        $("#org_list").html(template(data.data));

                        $('#org_tree').treegrid();
                        if (showAll){
                            $('#org_tree').treegrid('expandAll');
                        } else {
                            $('#org_tree').treegrid('collapseAll');
                        }
                    }
                })
            },
            loadOrgIncomeCompanyData: function (OrgId, pageNumber, pageSize) {
                var that = this;

                $("#indexMask").show();

                let s_id = $("#s_id").val();
                let s_name = $("#s_name").val();

                // let s_create_time_begin = $("#s_create_time_begin").val();
                // let s_create_time_end = $("#s_create_time_end").val();

                SYS.Core.ajax({
                    url: "base/orgIncomeCompany/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        OrgId: OrgId
                    },
                    success: function (data) {
                        $("#indexMask").hide();
                        let obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable1").bootstrapTable('destroy');
                        $('#myTable1').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            // clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                // {field: 'checked', checkbox: true} ,
                                {field: 'Id', title: '编号', align: 'center'},
                                {field: 'OrgId', title: '组织架构信息', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value > 0) {
                                            let OrgName = row.OrgName;
                                            html = OrgName + "(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'CompanyId', title: '公司信息', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value) {
                                            let companyCode = row.CompanyCode || "";
                                            let companyName = row.CompanyName || "";
                                            html = companyCode + "-" + companyName + "<br>(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        return '<a href="javascript:void(0)" onclick="BASE.Org.toOrgIncomeCompanyRemove(' + row.Id + ',' + OrgId + ')" class="text-do-remove"><i class="fa fa-trash"></i> 删除</a>';
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadOrgIncomeCompanyData(OrgId,number, size);
                            },
                            onRefreshTable: function () {
                                that.loadOrgIncomeCompanyData(OrgId);
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });

                        that.showDiv("company_div")
                    }
                });
            },
            loadOrgFeeCompanyCostCenterData: function (OrgId, pageNumber, pageSize) {
                var that = this;

                $("#indexMask").show();
                let s_id = $("#s_id").val();
                let s_name = $("#s_name").val();

                // let s_create_time_begin = $("#s_create_time_begin").val();
                // let s_create_time_end = $("#s_create_time_end").val();

                SYS.Core.ajax({
                    url: "base/orgFeeCompanyCostCenter/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        OrgId: OrgId
                    },
                    success: function (data) {
                        $("#indexMask").hide();
                        let obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable2").bootstrapTable('destroy');
                        $('#myTable2').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            // clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                // {field: 'checked', checkbox: true} ,
                                {field: 'Id', title: '编号', align: 'center'},
                                {field: 'OrgId', title: '组织架构信息', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value > 0) {
                                            let OrgName = row.OrgName || "";
                                            html = OrgName + "(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'CompanyId', title: '公司信息', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value) {
                                            let companyCode = row.CompanyCode || "";
                                            let companyName = row.CompanyName || "";
                                            html = companyCode + "-" + companyName + "<br>(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'CostCenterId', title: '费用信息', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value) {
                                            let CostCenterCode = row.CostCenterCode || "";
                                            let CostCenterName = row.CostCenterName || "";
                                            html = CostCenterCode + "-" + CostCenterName + "<br>(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        return '<a href="javascript:void(0)" onclick="BASE.Org.toOrgFeeCompanyCostCenterRemove(' + row.Id + ',' + OrgId + ')" class="text-do-remove"><i class="fa fa-trash"></i> 删除</a>';
                                    }
                                }
                            ],
                            formatLoadingMessage:function() {
                                return "加载中···";
                            },
                            onPageChange: function(number, size){
                                that.loadOrgFeeCompanyCostCenterData(OrgId,number, size);
                            },
                            onRefreshTable: function () {
                                that.loadOrgFeeCompanyCostCenterData(OrgId);
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;

                $(".i-checks").iCheck({checkboxClass:"icheckbox_square-orange", radioClass:"iradio_square-orange"});

                // 定义编辑框form
                let $form = $("#fm");

                // 查询
                $("#search-toolbar").on('click', "#btn_search", function () {
                    let val = $('#s_OrgVersionId').val();
                    let id = $('#s_OrgVersionId').attr('data-id');
                    if (val == "") {
                        $.messager.popup("请选择组织机构版本，在进行查询", "warn");
                        return;
                    }
                    that.loadData(id);
                }).on("keydown ", "input", function (e) {
                    if (e.keyCode == 13) {
                        let val = $('#s_OrgVersionId').val();
                        let id = $('#s_OrgVersionId').attr('data-id');
                        if (val == "") {
                            $.messager.popup("请选择组织机构版本，在进行查询", "warn");
                            return;
                        }
                        that.loadData(id);
                    }
                });

                // 新增
                $("#btn_add_company").on('click', function () {
                    that.clearDatas();

                    $('#myModal1').modal('show');
                    that.showDiv('company_div');
                });

                // 新增
                $("#btn_add_costCenter").on('click', function () {
                    that.clearDatas();

                    $('#myModal2').modal('show');
                    that.showDiv('costCenter_div');
                });

                // 报表项目父级
                $("#CompanyId,#CompanyId2").on('click', function () {
                    DOCTOR.Select.showCompany(this);
                });

                // 报表项目父级
                $("#CostCenterId").on('click', function () {

                    let Id2 = $('#CompanyId2').attr('data-id') || "";
                    let val2 = $('#CompanyId2').val();

                    if(Id2=="" && val2 == "") {
                        $.messager.popup("请选择一个关联的公司，在选择成本", 'error');
                        return;
                    }

                    DOCTOR.Select.showCostCenter(this);
                });

                // 报表项目父级
                $("#s_OrgVersionId").on('click', function () {
                    DOCTOR.Select.showOrgVersion(this);
                });

                // 返回
                $(".back_list").on('click', function () {
                    that.showDiv('main_div');
                });

                $('#fm').bootstrapValidator({
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // Company: {
                        //     validatorg: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                        // sort: {
                        //     validatorg: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         },
                        //         regexp: {
                        //             regexp: /^[1-9][0-9]*$/,
                        //             message: '请输入正整数'
                        //         }
                        //     }
                        // }
                    },
                    //提交后，整个页面会刷新
                    //submitHandler: function(validator, form, submitButton) {
                    //    that.save);
                    //}
                }).on('success.form.bv', function (e) { //使用此方法可以ajax
                    e.preventDefault();
                    //保存菜单
                    that.save();
                });

                $('#fm_company').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // Name: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    let Id = $("#CompanyId").attr('data-id') || "";
                    let val = $("#CompanyId").val();

                    if(Id == "" && val == "") {
                        $.messager.popup("请选择一个关联的公司，在提交", 'error');
                        $('#fm_company').bootstrapValidator('resetForm', true);
                        return;
                    }
                    that.saveOrgIncomeCompany();
                });

                $('#fm_costCenter').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // Name: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    let val = $("#CompanyId2").val();
                    let Id = $("#CompanyId2").attr('data-id') || "";

                    if(Id == "" && val == "") {
                        $.messager.popup("请选择一个关联的公司，在提交", 'error');
                        $('#fm_costCenter').bootstrapValidator('resetForm', true);
                        return;
                    }

                    let val2 = $("#CostCenterId").val();
                    let Id2 = $("#CostCenterId").attr('data-id') || "";
                    if(Id2 == "" && val2 == "") {
                        $.messager.popup("请选择一个关联的成本，在提交", 'error');
                        $('#fm_costCenter').bootstrapValidator('resetForm', true);
                        return;
                    }
                    that.saveOrgFeeCompanyCostCenter();
                });

                //清空验证信息(必须)
                $('#myModal').on('hide.bs.modal', function() {
                    $("#fm input[name='_id']").val('');
                    $("#fm input[name='parent_id']").val('');
                    $("#fm input[name='Name']").val('');

                    $("#fm input[name='Flag'][value='0']").iCheck('check');

                    $("#fm input[name='NodeLevel']").val('');
                    $("#fm input[name='sort']").val(1);

                    $('#fm').bootstrapValidator('resetForm', true);
                });
            },
            edit: function (id) {
                //根据id获取菜单信息
                SYS.Core.ajax({
                    url: "base/org/detail",
                    common: {},
                    data: { Id: id },
                    success: function (data) {
                        if(data.code == 1){
                            //填充表单
                            let obj = data.data;
                            let flag = obj.Flag;

                            $("#fm input[name='_id']").val(obj.Id);
                            $("#fm input[name='parent_id']").val(obj.ParentId);
                            $("#fm input[name='OrgVersionId']").val(obj.OrgVersionId);
                            $("#fm input[name='Name']").val(obj.Name);
                            $("#fm input[name='Flag'][value='" + flag + "']").iCheck('check');

                            $("#fm input[name='NodeLevel']").val(obj.NodeLevel);
                            $("#fm input[name='sort']").val(obj.sort);
                        }else{
                            $.messager.popup('加载数据失败，请稍后再试','error');
                        }
                    }
                });
                $('#myModal').modal({backdrop: 'static', keyboard: false});
                $('#myModal').modal('show');
            },
            save: function () {
                var that = this;

                let url = '';
                let id = $("#fm input[name='_id']").val();
                if(id==''){
                    url = 'base/org/save';
                }else{
                    url = 'base/org/edit';
                }
                let parent_id = $("#fm input[name='parent_id']").val();
                let Name = $("#fm input[name='Name']").val();
                let Flag = $("input[name='Flag']:checked").val()

                let OrgVersionId = $('#OrgVersionId').val();

                let NodeLevel = $("#NodeLevel").val();
                let sort = $("#fm input[name='sort']").val();

                SYS.Core.ajax({
                    url: url,
                    common: {},
                    data: {
                        Id: id ? id : 0,
                        ParentId: parent_id ? parent_id : 0,
                        Name: Name,
                        Flag: Flag,
                        OrgVersionId: OrgVersionId,
                        NodeLevel: NodeLevel,
                        sort: sort
                    },
                    success: function (data) {
                        if(data.code == 1){
                            $('#myModal').modal('hide');
                            $.messager.popup('保存成功','success');
                            that.loadData(OrgVersionId, true);
                        }else{
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup('保存失败','error');
                        }
                    }
                });
            },
            saveOrgIncomeCompany: function () {
                var that = this;

                let OrgId = $("#OrgId").val();
                let CompanyId = $("#CompanyId").attr('data-id');

                SYS.Core.ajax({
                    url: 'base/orgIncomeCompany/save',
                    common: {},
                    data:{
                        Id: 0,
                        OrgId: OrgId,
                        CompanyId: CompanyId
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            that.loadOrgIncomeCompanyData(OrgId);
                            $('#myModal1').modal('hide');
                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            saveOrgFeeCompanyCostCenter: function () {
                var that = this;

                let OrgId2 = $("#OrgId2").val();
                let CompanyId2 = $("#CompanyId2").attr('data-id');
                let CostCenterId = $("#CostCenterId").attr('data-id');

                SYS.Core.ajax({
                    url: 'base/orgFeeCompanyCostCenter/save',
                    common: {},
                    data:{
                        Id: 0,
                        OrgId: OrgId2,
                        CompanyId: CompanyId2,
                        CostCenterId: CostCenterId
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            that.loadOrgFeeCompanyCostCenterData(OrgId2);
                            $('#myModal2').modal('hide');
                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            addChild: function (id, NodeLevel= "", OrgVersionId = "") {
                if (id === 0) {
                    let val = $("#s_OrgVersionId").val() || "";
                    OrgVersionId = $("#s_OrgVersionId").attr('data-id') || "";
                    if(OrgVersionId == "" && val == "") {
                        $.messager.popup("搜索条件请选择一个关联组织机构版本，在添加", 'error');
                        $('#fm').bootstrapValidator('resetForm', true);
                        return;
                    }
                }

                $("#fm input[name='parent_id']").val(id); //绑定父菜单ID
                $("#fm input[name='OrgVersionId']").val(OrgVersionId); //绑定父菜单ID

                if(NodeLevel == ""){
                    $("#fm input[name='NodeLevel']").val(0);                     // 节点所在层级
                } else {
                    $("#fm input[name='NodeLevel']").val(Number(NodeLevel) + 1);  // 节点所在层级
                }

                $('#myModal').modal('show');
            },
            delete: function (id) {
                var that = this;
                let OrgVersionId = $('#s_OrgVersionId').attr('data-id');
                $.messager.confirm('确定要删除选择的组织架构吗？如果存在子组织架构，将一并删除？', function () {
                    SYS.Core.ajax({
                        url: "base/org/del",
                        common: {},
                        data: {Id: id},
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, 'success');
                                that.loadData(OrgVersionId, true);
                            }else{
                                $.messager.popup('删除失败，请稍后再试', 'error');
                            }
                        }
                    })
                });
            },
            toOrgIncomeCompanyRemove: function (id, OrgId) {
                var that = this;

                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "base/orgIncomeCompany/delete",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");

                                that.loadOrgIncomeCompanyData(OrgId);
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            toOrgFeeCompanyCostCenterRemove: function (id, OrgId) {
                var that = this;
                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "base/orgFeeCompanyCostCenter/delete",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");
                                that.loadOrgFeeCompanyCostCenterData(OrgId);
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            toOrgIncomeCompany: function (id) {
                var that = this;

                // 设置reportItemId
                $("#fm_company #OrgId").val(id);
                $("#myTable1").bootstrapTable('destroy');

                this.loadOrgIncomeCompanyData(id);
                that.showDiv('company_div');

                // SYS.Core.ajax({
                //     url: 'base/profitReportItem/detail',
                //     common: {},
                //     data: {
                //         Id: id || 0
                //     },
                //     success: function (data) {
                //         if (data.code == 1) {
                //             var obj = data.data;
                //
                //             that.showDiv('edit_div');
                //         }
                //     }
                // });
            },
            toOrgFeeCompanyCostCenter: function (id) {
                var that = this;

                // 设置reportItemId
                $("#fm_costCenter #OrgId2").val(id);
                $("#myTable2").bootstrapTable('destroy');

                this.loadOrgFeeCompanyCostCenterData(id);
                that.showDiv('costCenter_div');

                // SYS.Core.ajax({
                //     url: 'base/profitReportItem/detail',
                //     common: {},
                //     data: {
                //         Id: id || 0
                //     },
                //     success: function (data) {
                //         if (data.code == 1) {
                //             var obj = data.data;
                //
                //             that.showDiv('edit_div');
                //         }
                //     }
                // });
            },
            showDiv: function (div) {
                var divs = ['main_div', 'company_div', 'costCenter_div'];

                for(var i=0; i<divs.length; i++){
                    $("#" + divs[i]).hide();
                }
                $("#" + div).show();
            }
        }
    });

    BASE.Org.init();
});
